<template>
  <BasicTree
    v-if="treeData.length"
    treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
    :clickRowToExpand="false"
    :treeData="treeData"
    :fieldNames="{ key: 'key', title: 'title' }"
    @select="handleSelect"
    :defaultExpandAll="true"
    style="background-color: rgb(248, 239, 232)"
  />
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, onBeforeMount } from 'vue';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getUserDeptsTree } from '/@/api/project/dept';

  import { useRouter } from 'vue-router';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);

      const router = useRouter();
      const pcode = ref('');

      onBeforeMount(() => {
        //获取路由地址传参 url中的参数使用params获取
        // console.log('当前路由参数：', router.currentRoute.value.params);
        if (router.currentRoute.value.params.project) {
          pcode.value = router.currentRoute.value.params.project;
          // console.log('tree pcode', pcode.value);
        }
        getDeptList();
      });

      async function getDeptList() {
        getUserDeptsTree({ pcode: pcode.value })
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            treeData.value = res as unknown as TreeItem[];
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      function handleSelect(keys) {
        emit('select', keys[0]);
      }

      onMounted(() => {
        getDeptList();
      });
      return { treeData, handleSelect, getDeptList };
    },
  });
</script>
